package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务端
 */
public class Server {
    // 服务端变量
    private ServerSocket serverSocket;
    //设计集合存放所以客户端输出流，用于群发
    private Map<String,PrintWriter> allOut = new HashMap<>();

    public Server() {
        try {
            System.out.println("正在启动服务端....");
            // 创建一个服务端实例，监听8088端口
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完成");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            while (true){
                System.out.println("等待客户端连接");
                Socket socket =serverSocket.accept();
                System.out.println("一个客户端连接了");

                //启动一个线程来处理客户端的交互
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }
        } catch (IOException e) {

        }
    }

    public static void main(String[] args) {
        Server server= new Server();
        server.start();
    }

    private  class  ClientHandler implements Runnable{
        private Socket socket;
        private String host;//记录客户端地址
        private String nickName;//记录客户端昵称
        public ClientHandler(Socket socket){
            this.socket=socket;
            host =socket.getInetAddress().getHostAddress();//通过socket获取远端计算机地址
        }
        public void run(){
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);




                OutputStream ot = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(ot,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw =new PrintWriter(bw,true);


                nickName = br.readLine();//读取客户端发过来的昵称
                synchronized (allOut){//向集合中添加元素需要添加同步
                    allOut.put(nickName,pw);//将该客户端输出流存入Map中
                }
                sendMessageToAll("上线了，当前在线人数:"+allOut.size());//通知所有客户端，该用户上线了



                String message;
                while ((message=br.readLine())!=null){
                    if (message.startsWith("@")){
                        sendMessageToSomeone(message);
                }else {
                        sendMessageToAll("说："+ message);
                    }
            } }catch (IOException e) {
            }finally {
                synchronized (allOut){
                    allOut.remove(nickName);
                }
                sendMessageToAll("下线了，当前在线人数："+allOut.size());

                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void sendMessageToAll(String message){
            System.out.println(nickName+"["+host+"]"+ message);
            synchronized (allOut){//群发时也要保证多个线程同步处理
                for (PrintWriter o:allOut.values()){
                    o.println(nickName+"["+host+"]"+ message);
                }
            }
        }

        private void sendMessageToSomeone(String message){
            if (message.matches("@.+:.+")) {
                String toNickName = message.substring(1, message.indexOf(":"));
                if (allOut.containsKey(toNickName)) {//在线
                    PrintWriter pw = allOut.get(toNickName);
                    String toMessage = message.substring(message.indexOf(":") + 1);
                    pw.println(nickName + "悄悄对你说：" + toMessage);
                } else {
                    PrintWriter pw = allOut.get(nickName);
                    pw.println("该用户["+toNickName+"]不在线！");
                }

            }else {
                    PrintWriter pw = allOut.get(nickName);
                    pw.println("私聊格式不正确");
                }
            }
    }
}
